<template>
  <div
          :style="$el&&$el.style&&$el.style.cssText||'width:120px;'"
  >
      <el-select v-model="innerValue"
                 :disabled="$attrs['disabled']"
                 :placeholder="$attrs['placeholder']"
                 clearable=""
                 @change="(val)=>changeValue(val)"
                 :size="$attrs['size']"
                 :multiple="$props.mul"
                 :style="$el&&$el.style&&$el.style.cssText||'width:120px;'"
      >
          <el-option
                  v-for="item in $data.options"
                  :key="item.value"
                  :value="item.value||''"
                  :label="item.label"
          />
      </el-select>
  </div>
</template>
<script>
  import { ajaxDicList } from '@/utils/dic.js';
  import * as lodash from 'lodash';
  
  function safeParseInt(str) {
    
    if (!str) {
      return '';
    }
    return parseInt(str);
  }
  
  export default {
    data() {
      return {
        innerValue: '',
        options: [],
        style123: '',
      };
    },
    props: {
      code: { type: [String, Number], require: true },
      value: { type: [String, Number, Array] },
      //check 模式
      checkMode: { type: Boolean, default: false },
      //按钮模式
      buttonMode: { type: Boolean, default: true },
      mul: { type: Boolean, default: () => false },
    },
    mounted() {
      
      this.ajaxList().then(res => {
        if (this.$props.value != undefined && this.$props.value != null) {
          this.innerValue = safeParseInt(this.$props.value);
        }
      });
    },
    watch: {
      value(_val) {
        this.innerValue = safeParseInt(_val || '');
        
        //处理 style
        if (this.$el && this.$el.style) {
          this.style123 = this.$el.style.cssText;
        }
      },
    },
    methods: {
      
      
      changeValue(val) {
        if (this.$props.mul) {
          var valueArray = val || [];
          this.$emit('change', valueArray);
          var valueWithData = this.options.filter(item => valueArray && valueArray.includes(item.value));
          this.$emit('change2', valueWithData);
        } else {
          this.innerValue = val;
          this.$emit('input', val);
          var selectOne = lodash.find(this.options, item => item.value == val);
          this.$emit('change', val);
          //change2 返回的是一个对象
          this.$emit('change2', selectOne);
        }
        
      },
      ajaxList() {
        var self = this;
        if (!this.$props.code) return Promise.resolve([]);
        return ajaxDicList(this.$props.code).then(list => {
          
          var templist = list || [];
          this.$data.options = templist.map(item => {
            item.value = safeParseInt(item.value) || 0;
            
            return item;
          });
        });
      },
    },
  };
</script>
